﻿@typeparam TItem where TItem : RealServer

<MDataTable Items="@Items"
            Loading="_isLoading"
            HideDefaultFooter
            Dense>
    <HeaderContent>
        <MTh>IP地址</MTh>
        <MTh>端口</MTh>
        <MTh>权重</MTh>
        <MTh>健康检查</MTh>
        <MTh>操作</MTh>
    </HeaderContent>
    
    <ItemContent Context="item">
        <MTd>@item.Item.IpAddress</MTd>
        <MTd>@item.Item.Port</MTd>
        <MTd>@item.Item.Weight</MTd>
        <MTd>
            @if (item.Item.HealthCheck != null)
            {
                <MChip Small Color="primary">
                    @GetHealthCheckType(item.Item.HealthCheck)
                </MChip>
            }
        </MTd>
        <MTd>
            <MButton Icon
                     Color="primary"
                     OnClick="@(() => EditItem(item.Item))">
                <MIcon>mdi-pencil</MIcon>
            </MButton>
            <MButton Icon
                     Color="error"
                     OnClick="@(() => RemoveItem(item.Item))">
                <MIcon>mdi-delete</MIcon>
            </MButton>
        </MTd>
    </ItemContent>
    
    <FooterContent>
        <MCol Cols="12">
            <MButton Color="primary"
                     Outlined
                     Block
                     OnClick="OnAdd">
                <MIcon Left>mdi-plus</MIcon>
                添加真实服务器
            </MButton>
        </MCol>
    </FooterContent>
</MDataTable>

@if (_editDialog)
{
    <RealServerEditorDialog @bind-Value="_editDialog"
                           @bind-Item="_currentItem"
                            TItem="TItem"
                           OnSave="HandleSave" />
}

@code {
    [Parameter]
    public List<TItem> Items { get; set; }

    [Parameter]
    public EventCallback<List<TItem>> ItemsChanged { get; set; }

    [Parameter]
    public EventCallback OnAdd { get; set; }

    [Parameter]
    public EventCallback<TItem> OnRemove { get; set; }

    [Inject]
    public IPopupService PopupService { get; set; }

    private bool _isLoading = false;
    private bool _editDialog = false;
    private TItem _currentItem;

    private string GetHealthCheckType(HealthCheck check)
    {
        return check switch
        {
            TcpHealthCheck _ => "TCP检查",
            HttpHealthCheck _ => "HTTP检查",
            SslHealthCheck _ => "SSL检查",
            _ => "未知检查"
        };
    }

    private async Task EditItem(TItem item)
    {
        _currentItem = item;
        _editDialog = true;
    }

    private async Task RemoveItem(TItem item)
    {
        var confirm = await PopupService.ConfirmAsync(
            "确认删除",
            $"确定要删除真实服务器吗?",
            "删除",
            AlertTypes.Warning);
        
        if (confirm)
        {
            await OnRemove.InvokeAsync(item);
        }
    }

    private async Task HandleSave(TItem item)
    {
        _editDialog = false;
        await ItemsChanged.InvokeAsync(Items);
    }
}